package com.meng.system.service.impl.auth;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meng.system.domain.vo.RoleSaveVO;
import com.meng.system.domain.vo.SysMenuVO;
import com.meng.system.domain.vo.SysRoleVO;
import com.meng.system.mapper.auth.SysMenuMapper;
import com.meng.system.mapper.auth.SysRoleMapper;
import com.meng.system.service.auth.SysRoleService;
import com.meng.system.utils.CopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 系统角色表 服务实现类
 * </p>
 *
 * @author Xu Meng
 * @since 2021-01-14
 */
@Slf4j
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRoleVO> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 获取role 分页数据
     * @param pageNum 当前页数
     * @param pageSize 每页行数
     * @param search 搜索字段
     * @return 返回结果集
     */
    @Override
    public Page<SysRoleVO> findRoleListPage(int pageNum, int pageSize, String search) {

        Page<SysRoleVO> page = new Page<>(pageNum, pageSize);
        List<SysRoleVO> result = sysRoleMapper.findRoleListPage(search,page);
        page.setRecords(result);
        return page;
    }

    /**
     * 新增or修改角色
     * @param role 新增对象
     * @return
     */
    @Override
    public boolean saveOrUpdateRole(RoleSaveVO role) throws Exception{
        SysRoleVO roleVO = new SysRoleVO();
        if (Objects.isNull(role.getRoleId())) {
            //新增
            roleVO.setCreateTime(new Date());
            roleVO.setUpdateTime(new Date());
            CopyUtils.copy(role,roleVO);
            if(sysRoleMapper.insert(roleVO)>0){
                List<SysMenuVO> menus = role.getMenus();
                return sysMenuMapper.saveMenuRole(menus,role.getRoleId());
            }else {
                return false;
            }
        } else {
            //修改
            roleVO.setUpdateTime(new Date());
            CopyUtils.copy(role,roleVO);
            return sysRoleMapper.updateById(roleVO)>0;
        }

    }
}
